package com.linked.basemanage.util;


import com.linked.basemanage.config.MinioProp;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.time.LocalDate;

/**
 * @author :dbq
 * @date : 2023/2/14 16:09
 * @description : desc
 */

@Slf4j
@Component
public class MinioUtils {

    @Autowired
    private MinioClient client;
    @Autowired
    private MinioProp minioProp;

    /**
     * 创建bucket
     *
     * @param bucketName bucket名称
     */
    @SneakyThrows
    public void createBucket(String bucketName) {
        if (!client.bucketExists(bucketName)) {
            client.makeBucket(bucketName);
        }
    }

    /**
     * 上传文件
     *
     * @param file       文件
     * @param bucketName 存储桶
     * @return
     */
    public String uploadFile(File file, String minioUrl) throws Exception {
        String url = null;
        // 判断上传文件是否为空
        if (null == file || 0 == file.length()) {
            log.info("上传文件不能为空");
            return null;
        }
        InputStream is = null;
        try {
            // 判断存储桶是否存在
            createBucket(minioProp.getBucketName());
            // 文件名
            String filename = file.getAbsolutePath();
            // 新的文件名 = 存储桶名称_时间戳.后缀名
            filename = minioUrl + "/" + LocalDate.now() + "/" + System.currentTimeMillis() + filename.substring(filename.lastIndexOf("."));
            //
            is = new FileInputStream(file);
            // 开始上传
            PutObjectArgs tempArgs = PutObjectArgs.builder()
                    .bucket(minioProp.getBucketName())
                    .contentType(Files.probeContentType(file.toPath()))
                    .object(filename)
                    .stream(is, Long.valueOf(is.available()), PutObjectArgs.MAX_PART_SIZE)
                    .build();
            client.putObject(tempArgs);
            url = minioProp.getEndpoint() + "/" + minioProp.getBucketName() + "/" + filename;
        } catch (Exception e) {
            log.error("上传Minio服务器失败", e);
            return null;
        } finally {
            if (is != null) {
                is.close();
            }
        }
        return url;
    }

//    public String uploadFile(InputStream inputStream, String fileName, String minioUrl) throws Exception {
//        String url = null;
//        // 判断上传文件是否为空
//        if (null == inputStream) {
//            log.info("上传文件不能为空");
//            return null;
//        }
//        if (StringUtils.isEmpty(bucket)){
//            bucket = minioProp.getBucket();
//        }
//        try {
//            // 判断存储桶是否存在
//            createBucket(minioProp.getBucket());
//            // 新的文件名 = 存储桶名称_时间戳.后缀名
//            String filename = minioUrl + "/" + LocalDate.now() + "/" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
//
//            // 开始上传
//            PutObjectArgs tempArgs = PutObjectArgs.builder()
//                    .bucket(bucket)
//                    .contentType(Files.probeContentType(new File(fileName).toPath()))
//                    .object(filename)
//                    .stream(inputStream, Long.valueOf(inputStream.available()), PutObjectArgs.MAX_PART_SIZE)
//                    .build();
//            client.putObject(tempArgs);
//            url = minioProp.getEndpoint() + "/" + minioProp.getBucket() + "/" + filename;
//        } catch (Exception e) {
//            log.error("上传Minio服务器失败", e);
//            return null;
//        } finally {
//            if (inputStream != null) {
//                inputStream.close();
//            }
//        }
//        return url;
//    }

    public String uploadFile(InputStream inputStream, String bucket, String minioUri, String suffix) throws Exception {
        String url = null;
        // 判断上传文件是否为空
        if (null == inputStream) {
            log.info("上传文件不能为空");
            return null;
        }
        if (StringUtils.isEmpty(bucket)) {
            bucket = minioProp.getBucketName();
        }
        try {
            // 判断存储桶是否存在
            createBucket(bucket);
            // 新的文件名 = 存储桶名称_时间戳.后缀名
            String filename = minioUri + "/" + System.currentTimeMillis() + suffix;
            // 开始上传
            PutObjectArgs tempArgs = PutObjectArgs.builder()
                    .bucket(bucket)
                    .contentType(Files.probeContentType(new File(filename).toPath()))
                    .object(filename)
                    .stream(inputStream, Long.valueOf(inputStream.available()), PutObjectArgs.MAX_PART_SIZE)
                    .build();
            client.putObject(tempArgs);
            url = bucket + "/" + filename;
        } catch (Exception e) {
            log.error("上传Minio服务器失败", e);
            throw new RuntimeException(e);

        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return url;
    }
}
